package com.chen.utils.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.chen.root.base.R;
import com.chen.utils.entity.DatasourceFill;
import com.chen.utils.entity.Fill;
import com.chen.utils.mapper.DatasourceFillMapper;
import com.chen.utils.mapper.FillMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: ~龙~
 * @date: 2023/7/20 14:42
 **/
@Slf4j
@Validated
@RestController
@RequestMapping("/fill")
@Api(tags = "自动填充配置管理API")
public class FillController {

    @Resource
    private FillMapper fillMapper;
    @Resource
    private DatasourceFillMapper datasourceFillMapper;

    @GetMapping("/list")
    @ApiOperation("获取所有自动填充配置")
    public R<List<Fill>> list(){
        return R.ok(fillMapper.selectList(Wrappers.lambdaQuery()));
    }

    @PostMapping("/save")
    @ApiOperation("保存自动填充配置")
    public R<Boolean> save(@RequestBody @Validated Fill fill){
        if (StrUtil.isNotBlank(fill.getId())){
            fillMapper.updateById(fill);
        }else {
            fillMapper.insert(fill);
        }
        return R.ok(null,"操作成功!");
    }

    @GetMapping("/delete")
    @ApiOperation("删除自动填充配置")
    public R<Boolean> delete(String fillId, String datasourceId){
        datasourceFillMapper.delete(Wrappers.lambdaQuery(DatasourceFill.class)
                .eq(DatasourceFill::getDatasourceId, datasourceId)
                .eq(DatasourceFill::getFillId, fillId)
        );
        return R.ok(null,"操作成功!");
    }

    @GetMapping("/getByDatasourceId")
    @ApiOperation("根据数据源id获取策略配置")
    public R<List<Fill>> getByDatasourceId(String datasourceId){
        List<DatasourceFill> dfs = datasourceFillMapper.selectList(
                Wrappers.lambdaQuery(DatasourceFill.class).eq(DatasourceFill::getDatasourceId, datasourceId)
        );
        if (dfs.size() == 0){
            return R.ok(Collections.emptyList());
        }
        List<String> fillIds = dfs.stream().map(DatasourceFill::getFillId).collect(Collectors.toList());
        return R.ok(fillMapper.selectBatchIds(fillIds));
    }
}
